<template>
  <div class="violation-chart-container">
    <h2>学生归宿情况统计</h2>
    <div class="chart-header">
      <el-button 
        type="primary" 
        size="small" 
        @click="refreshChart"
        :loading="loading"
      >
        <i class="el-icon-refresh"></i> 刷新数据
      </el-button>
    </div>
    <div ref="chart" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getAtqk } from '@/api/classinfo/classinfo'

export default {
  name: 'AttendanceStatsChart',
  data() {
    return {
      chart: null,
      statsData: [
        { name: '正常', value: 0 },
        { name: '晚归', value: 0 },
        { name: '未归', value: 0 }
      ],
      loading: false
    }
  },
  mounted() {
    this.initChart()
    this.fetchAttendanceStats()
  },
  methods: {
    initChart() {
      if (!this.$refs.chart) return
      
      this.chart = echarts.init(this.$refs.chart)
      this.updateChart()
      window.addEventListener('resize', this.handleResize)
    },
    
    async fetchAttendanceStats() {
  this.loading = true;
  try {
    const response = await getAtqk();
    // 直接从 response 取 stats
    const stats = response.stats || {}; 

    console.log('Received data:', stats); 

    this.statsData = [
      { name: '正常', value: stats['正常'] || 0 },
      { name: '晚归', value: stats['晚归'] || 0 },
      { name: '未归', value: stats['未归'] || 0 }
    ];

    this.updateChart();
  } catch (error) {
    console.error('获取归宿统计数据失败:', error);
    this.$message.error('获取数据失败，请稍后重试');
  } finally {
    this.loading = false;
  }
},
    
    refreshChart() {
      this.fetchAttendanceStats()
    },
    
    updateChart() {
      if (!this.chart) return
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: '{b}: {c}人'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.statsData.map(item => item.name),
          axisLabel: {
            interval: 0,
            rotate: 0,
            fontSize: 12
          }
        },
        yAxis: {
          type: 'value',
          name: '人数',
          nameLocation: 'middle',
          nameGap: 30
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            data: this.statsData.map(item => item.value),
            itemStyle: {
              color: params => {
                const colorMap = {
                  '正常': '#67C23A',
                  '晚归': '#E6A23C',
                  '未归': '#F56C6C'
                }
                return colorMap[this.statsData[params.dataIndex].name] || '#409EFF'
              }
            },
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      }
      
      this.chart.setOption(option)
    },
    
    handleResize() {
      this.chart && this.chart.resize()
    }
  },
  
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      window.removeEventListener('resize', this.handleResize)
    }
  }
}
</script>

<style scoped>
.violation-chart-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}

h2 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
}
</style>